package model

import (
	db "mwwow_service_go/database"
)

type Message struct {
	ID         int    `json:"id",form:"id"`
	CreateTime int    `json:"createTime",form:"createTime"`
	Content    string `json:"content",form:"content"`
	EditorName string `json:"editorName",form:"editorName"`
}

// 增加留言
func (m *Message) AddMsg() (id int64, err error) {
	sql := "INSERT INTO message(createTime,content,editorName) VALUES (?,?,?)"
	rs, err := db.SqlDB.Exec(sql, m.CreateTime, m.Content, m.EditorName)
	if err != nil {
		return
	}
	id, err = rs.LastInsertId()
	return
}

// 删除留言
func (m *Message) DeleteMsg(id string) (isSuccess bool, err error) {
	rs, err := db.SqlDB.Exec("DELETE FROM message WHERE ID=?", id)
	if err != nil {
		return
	}
	if num, _ := rs.RowsAffected(); num == 0 {
		return
	}
	isSuccess = true
	return
}

// 获取全部留言
func (m *Message) GetMsg() (messages []Message, err error) {
	messages = make([]Message, 0)
	rows, err := db.SqlDB.Query("SELECT * FROM message ORDER BY createTime DESC")
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		var message Message
		rows.Scan(&message.ID, &message.Content, &message.EditorName, &message.CreateTime)
		messages = append(messages, message)
	}
	if err = rows.Err(); err != nil {
		return
	}
	return
}
